import path, {dirname} from 'node:path'
import {fileURLToPath} from "node:url";
import {HttpBootstrap} from "boot/web"
import {IHttpContext, IMiddleware} from "@yedong/boot/types"
import config from './config/application'
import {
	Interceptor,
	ResponseMiddleware,
	TimeMiddleware,
	BodyParserMiddleware,
	ServeMiddleware
} from './middleware'

// const _dirname = dirname(fileURLToPath(import.meta.url))
const _dirname = (import.meta).dirname
const scanDirs = [
	path.resolve(_dirname, 'config'),
	path.resolve(_dirname, 'dao'),
	path.resolve(_dirname, 'service'),
	path.resolve(_dirname, 'controller')
]
console.log(`import.meta = `, import.meta)
console.log(`import.meta = `, import.meta)
console.log(`cwd = ${process.cwd()}`)
console.log(`_dirname = ${_dirname}`)
console.log(`scanDirs = ${scanDirs}`)

class AppHttpBoostrap extends HttpBootstrap {

	async getConfig(): Promise<any> {
		return config
	}

	async getScanDirs(): Promise<string[]> {
		return scanDirs
	}

	async getMiddlewares(): Promise<Array<IMiddleware>> {
		return [
			new Interceptor(),
			new TimeMiddleware(),
			new BodyParserMiddleware(), // body parser
			new ServeMiddleware(),  // 静态资源
			new ResponseMiddleware(),
		]
	}

	async onError(err: Error, ctx: IHttpContext) {
		console.log(err.message)
	}

	async onInit() {
		console.log('HttpBootstrap ==> onInit')
	}

	async beforeScanDirs() {
		console.log('HttpBootstrap ==> beforeScanDirs')
	}

	async afterScanDirs() {
		console.log('HttpBootstrap ==> afterScanDirs')
	}

	async beforeRegisterMiddlewares() {
		console.log('HttpBootstrap ==> beforeRegisterMiddlewares')
	}

	async afterRegisterMiddlewares() {
		console.log('HttpBootstrap ==> afterRegisterMiddlewares')
	}

	async beforeRegisterRoutes() {
		console.log('HttpBootstrap ==> beforeRegisterRoutes')
	}

	async afterRegisterRoutes() {
		console.log('HttpBootstrap ==> afterRegisterRoutes')
	}

	async onReady() {
		console.log('HttpBootstrap ==> onReady')
	}

	async onInitError(error: any) {
		console.log('HttpBootstrap ==> onInitError')
	}
}

const boostrap = new AppHttpBoostrap()

try {
	 await boostrap.start()
} catch (e) {
	console.log(e)
}

export default boostrap
